using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace Utils.WebFramework
{
    public class HttpObject
    {
        internal HttpObject()
        {

        }

        public HttpApplicationState Application
        {
            get { return application; }
        }

        public HttpServerUtility Server
        {
            get { return server; }
        }

        public HttpRequest Request
        {
            get { return request; }
        }

        public HttpResponse Response
        {
            get { return response; }
        }


        public Session Session
        {
            get
            {
                string sid = string.Empty;

                SessionManager sessionManager = SessionManager.GetSessionManager();
                HttpCookie httpCookie = request.Cookies["__sessionid"];
                if (httpCookie == null || string.IsNullOrEmpty(httpCookie.Value))
                {
                    sid = NewSession();
                }
                else
                {
                    sid = httpCookie.Value;
                    if (IsSessionExpired(sid))
                    {
                        sessionManager.RemoveSession(sid);
                        sid = NewSession();
                    }
                }

                Session session = sessionManager.GetSession(sid);
                session.Mark();

                return session;
            }
        }

        public string Domain 
        {
            get 
            {
                return "http://" + this.request.ServerVariables["HTTP_HOST"];
            }
        }

        private bool IsSessionExpired(string sid)
        {
            Session session = SessionManager.GetSessionManager().GetSession(sid);
            return session == null || session.dateTime < DateTime.Now;
        }

        private string NewSession()
        {
            string sid = Guid.NewGuid().ToString("N");

            HttpCookie httpCookie = new HttpCookie("__sessionid", sid);
            httpCookie.Expires = DateTime.MaxValue;
            this.response.AppendCookie(httpCookie);

            return sid;
        }

        internal HttpApplicationState application = null;
        internal HttpServerUtility server = null;
        internal HttpRequest request = null;
        internal HttpResponse response = null;
    }
}
